//
//  WebViewController.m
//  ERP
//
//  Created by QA on 16/3/15.
//  Copyright © 2016年 ShangHai HaoLei Software Technology Co., Ltd. All rights reserved.
//

#import "WebViewController.h"
#import <WebKit/WebKit.h>
#import "CLGifLoadView.h"
#import "YHWebViewProgressView.h"
#import "NSDictionary+DataFormat.h"

#import "WKWebViewJavascriptBridge.h"
//#import "NativeViewController.h"
//#import "ErrorViewController.h"
#import "BasicConfigurationHelper.h"

@interface WebViewController ()<WKNavigationDelegate,UIPrintInteractionControllerDelegate>

@property (nonatomic, strong) WKWebViewJavascriptBridge* bridge;
@property (nonatomic, strong) WebPushParameterModel* pushParameterModel;
@property (nonatomic, strong) WebPushParameterModel *searchPushParameterModel;

@property (nonatomic, strong) WKWebView* webView;
@property (nonatomic, strong) CLGifLoadView * gifLoading;
@property (nonatomic, strong) YHWebViewProgressView *progressView;

@property (nonatomic, strong) UILabel *titleLable;
@property (nonatomic, strong) UILabel *subLable;

@end

@implementation WebViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        [self setWebTitleNotStation: @"汇基云"];
    }
    return self;
}

- (id)initWithPushParameterModel:(WebPushParameterModel*)model
{
    self = [super init];
    if (self) {
        self.pushParameterModel = model;
        
        //添加时间戳防止缓存
        //NSTimeInterval interval = [[NSDate date] timeIntervalSince1970] * 1000;
        //self.pushParameterModel.URL = [self addUrl:model.URL ParameterKey:@"xtime" value:[NSString stringWithFormat:@"%f",interval]];
        
        //设置连接地址及相关设置
        self.pushParameterModel.URL = model.URL;
        NSArray *parament = [self getParamsWithUrlString:model.URL];
        NSDictionary *dictionary = parament.lastObject;
        [self setParameterFunction:dictionary];
        
        //设置标题名称
        if(model.SubTitle.length > 0) {
            [self setTitle:model.Title subtitle:model.SubTitle];
        } else {
            [self setTitle:model.Title];
        }
    }
    return self;
}

//URL数据拼凑
//- (NSString*)addUrl:(NSString*)url ParameterKey:(NSString *)key value:(NSString*)value
//{
//    if([url rangeOfString:@"?"].location ==NSNotFound){
//        url = [NSString stringWithFormat:@"%@?%@=%@",url,key,value];
//    } else {
//        url = [NSString stringWithFormat:@"%@&%@=%@",url,key,value];
//    }
//    return url;
//}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.edgesForExtendedLayout = UIRectEdgeAll;
    [self initWKWebView];
}

- (void)viewWillAppear:(BOOL)animated
{
    if(!_isNavigationBarDefault)
        [super viewWillAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    //清除进度条
    if(self.progressView) {
        _progressView.hidden = YES;
        [_progressView removeFromSuperview];
    }
}

- (void)initWKWebView
{
    self.webView = [[WKWebView alloc] initWithFrame:self.view.bounds];
    [self.webView setBackgroundColor:[UIColor whiteColor]];
    [self.view addSubview:_webView];
    [_webView makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view);
        make.left.equalTo(self.view);
        make.right.equalTo(self.view);
        make.bottom.equalTo(self.view);
    }];
    
    // 创建进度条
    self.progressView = [[YHWebViewProgressView alloc] initWithFrame:CGRectMake(0, 41, CGRectGetWidth(self.view.bounds), 2.5)];
    _progressView.progressBarColor = [UIColor whiteColor];
    _progressView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleBottomMargin;
    [_progressView useWkWebView:self.webView];
    if(!self.isHiddenNavigationProgress) [self.navigationController.navigationBar addSubview:_progressView];
    
    [WKWebViewJavascriptBridge enableLogging];
    _bridge = [WKWebViewJavascriptBridge bridgeForWebView:_webView];
    [self jsFunctionHandle:_bridge];
    [_bridge setWebViewDelegate:self];
    
    //添加进度条
    self.gifLoading = [[CLGifLoadView alloc] initWithFrame:self.view.bounds];
    _gifLoading.backgroundColor = [UIColor clearColor];
    _gifLoading.hidden = !self.isShowProgress;
    [self.view addSubview:_gifLoading];
    [_gifLoading makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view);
        make.left.equalTo(self.view);
        make.right.equalTo(self.view);
        make.bottom.equalTo(self.view);
    }];
    
    __weak WebViewController *viewController = self;
    __weak WebPushParameterModel *requestWeak = _pushParameterModel;
    [_gifLoading setRetryBlcok:^{
        NSLog(@"页面重试");
        viewController.gifLoading.hidden = !viewController.isShowProgress;
        [viewController.gifLoading setState:CLLoadStateLoading];
        [viewController loadURL:requestWeak];
    }];
    
    // 加载网页链接
    [self loadURL:_pushParameterModel];
}

// 重新加载网页链接
- (void)reloadLoading
{
    if(_pushParameterModel)
    [self loadURL:_pushParameterModel];
}

- (void)jumpViewController:(WebPushParameterModel*)pushParameterModel
{
    NSInteger codeType = pushParameterModel.CodeType;
    
    //CodeType类型：0异常、1原生、2网页
    if (codeType == CodeTypeNative) {
        //NativeViewController *viewController = [[NativeViewController alloc] init];
        //[self.navigationController pushViewController:viewController animated:YES];
        
    } else if (codeType == CodeTypeWeb)  {
        WebViewController *viewController = [[WebViewController alloc] initWithPushParameterModel:pushParameterModel];
        viewController.backResultDelagate = self;
        [self.navigationController pushViewController:viewController animated:YES];
        
    } else {
        //ErrorViewController *viewController = [[ErrorViewController alloc] init];
        //[self.navigationController pushViewController:viewController animated:YES];
    }
}

/**
 获取url中的参数并返回
 @param urlString 带参数的url
 @return @[NSString:无参数url, NSDictionary:参数字典]
 */
- (NSArray*)getParamsWithUrlString:(NSString*)urlString
{
    if(urlString.length==0) {
        NSLog(@"链接为空！");
        return @[@"",@{}];
    }
    
    //先截取问号
    NSArray*allElements = [urlString componentsSeparatedByString:@"?"];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];//待set的参数字典
    
    if(allElements.count==2) {
        //有参数或者?后面为空
        NSString*myUrlString = allElements[0];
        NSString*paramsString = allElements[1];
        
        //获取参数对
        NSArray*paramsArray = [paramsString componentsSeparatedByString:@"&"];
        if(paramsArray.count>=2) {
            for(NSInteger i =0; i < paramsArray.count; i++) {
                NSString*singleParamString = paramsArray[i];
                NSArray*singleParamSet = [singleParamString componentsSeparatedByString:@"="];
                
                if(singleParamSet.count==2) {
                    NSString*key = singleParamSet[0];
                    NSString*value = singleParamSet[1];
                    if(key.length>0|| value.length>0) {
                        [params setObject:value.length>0?value:@""forKey:key.length>0?key:@""];
                    }
                }
            }
            
        } else if(paramsArray.count==1) {
            //无 &。url只有?后一个参数
            NSString*singleParamString = paramsArray[0];
            NSArray*singleParamSet = [singleParamString componentsSeparatedByString:@"="];
            
            if(singleParamSet.count==2) {
                NSString*key = singleParamSet[0];
                NSString*value = singleParamSet[1];
                if(key.length>0|| value.length>0) {
                    [params setObject:value.length>0 ? value:@"" forKey:key.length>0 ? key:@""];
                }
            } else {
                //问号后面啥也没有 xxxx?  无需处理
            }
        }
        
        //整合url及参数
        return@[myUrlString,params];
        
    } else if(allElements.count>2) {
        NSLog(@"链接不合法！链接包含多个\"?\"");
        return @[@"",@{}];
    } else {
        NSLog(@"链接不包含参数！");
        return@[urlString,@{}];
    }
    
}

#pragma mark -
#pragma mark webview加载处理

- (void)loadURL:(WebPushParameterModel*)parameterModelURL
{
    // 加载网页链接
    if(parameterModelURL && parameterModelURL.URL){
        //转码url地址
        NSString *urlString = [parameterModelURL.URL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        //去除空格
        urlString = [urlString stringByReplacingOccurrencesOfString:@" " withString:@"+"];
        NSURL *url = [NSURL URLWithString:urlString];
        //判断是否合法
        if(!url) [self.gifLoading setState:CLLoadStateFailed];
        else [_webView loadRequest:[NSURLRequest requestWithURL:url]];
        
    } else {
        [self.gifLoading setState:CLLoadStateFailed];
    }
}

#pragma mark -
#pragma mark 参数设置及匹配

- (void)setParameterFunction:(NSDictionary*)dictionary
{
    NSString *showStationTitleKey = @"XT*IsShowStationTitle";//显示站点名称
    NSString *showStationTitleButtonKey = @"XT*IsShowStationTitleButton";//显示站点名称及切换按钮
//    NSString *showBackColorKey = @"XT*BackColor";//显背景颜色
    
    /******显示站点名称，副标题位置******/
    if([dictionary objectForKey:showStationTitleKey]){
        NSInteger isShow = [dictionary objectFormatIntegerForKey:showStationTitleKey];
        if(isShow == 1) {
            [self setWebTitleHaveStation];
        }
    }
    
    /******显示站点名称及切换按钮******/
    if([dictionary objectForKey:showStationTitleButtonKey]){
        NSInteger isShow = [dictionary objectFormatIntegerForKey:showStationTitleButtonKey];
        if(isShow == 1) {
            [self setWebTitleHaveStation];
            [self addStationToNavigationItem];
        }
    }
}

#pragma mark -
#pragma mark JS跳转分发注册

- (void)jsFunctionHandle:(WKWebViewJavascriptBridge*)bridge
{
    __weak typeof(self) weakSelf = self;
    
    #pragma mark 跳转窗体
    [bridge registerHandler:@"Native_PushWindowCallback" handler:^(id data, WVJBResponseCallback responseCallback) {
        NSLog(@"Native_PushWindowCallback called: %@", data);
        responseCallback(@"Response from testObjcCallback");
        
        //数据解析，并对数据完整性进行验证
        WebPushParameterModel *pushParameterModel = [WebPushParameterModel analysisJsonParameter:data];
        if (pushParameterModel == nil) return;
        [weakSelf jumpViewController:pushParameterModel];
        
    }];
    
    #pragma mark 关闭窗体
    [bridge registerHandler:@"Native_CloseWindowCallback" handler:^(id data, WVJBResponseCallback responseCallback) {
        NSLog(@"Native_CloseWindowCallback called: %@", data);
        responseCallback(@"Response from testObjcCallback");
        
        NSString *jsonString = @"";
        if([data isKindOfClass:[NSDictionary class]]){
            NSDictionary *dict = data;
            
            NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
            if (jsonData) jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
            
            jsonString = [jsonString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
            [jsonString stringByReplacingOccurrencesOfString:@"\n" withString:@""];
        } else {
            jsonString = [NSString stringWithFormat:@"%@",data];
        }
        
        //关闭窗体，返回页面参数
        if(weakSelf.backResultDelagate) [weakSelf.backResultDelagate backResultDataKey:weakSelf.key dataValue:jsonString];
        [self.navigationController popViewControllerAnimated:YES];
    }];
    
    #pragma mark 获取用户信息（简码、登陆信息）
    [bridge registerHandler:@"Native_GetUserInfoCallback" handler:^(id data, WVJBResponseCallback responseCallback) {
        NSLog(@"Native_CloseWindowCallback called: %@", data);
        ConfigurationCodeing *model = [ConfigurationHelper getConfigurationData];
        
        NSMutableDictionary *jsonDictionary = [NSMutableDictionary dictionary];
        [jsonDictionary setObject:model.briefCode forKey:@"CustomerCode"];//简码
        
        if ([NSJSONSerialization isValidJSONObject:jsonDictionary]){
            NSError *error;
            // 创造一个json从Data, NSJSONWritingPrettyPrinted指定的JSON数据产的空白，使输出更具可读性。
            NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDictionary options:NSJSONWritingPrettyPrinted error:&error];
            NSString *json =[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
            
            //返回页面参数
            responseCallback(json);
        }
    }];
    
    #pragma mark 获取基础配置信息（所有初始配置数据通过该接口获取）
    [bridge registerHandler:@"Native_BasicConfigurationCallback" handler:^(id data, WVJBResponseCallback responseCallback) {
        NSLog(@"Native_BasicConfigurationCallback called: %@", data);
        
        @try {
            StationInfoEntity *stationModel = [[GetUserStationService sharedService] getSelectStationEntity];
            BasicConfigurationCodeing *basicModel = [BasicConfigurationHelper getConfigurationData];
            
            NSMutableDictionary *jsonDictionary = [NSMutableDictionary dictionary];
            [jsonDictionary setObject:stationModel.stationId forKey:@"StationId"];
            [jsonDictionary setObject:stationModel.stationName forKey:@"StationName"];
            
            [jsonDictionary setObject:basicModel.startDayTime forKey:@"StartDayTime"];
            [jsonDictionary setObject:basicModel.endDayTime forKey:@"EndDayTime"];
            [jsonDictionary setObject:basicModel.startMonthTime forKey:@"StartMonthTime"];
            [jsonDictionary setObject:basicModel.endMonthTime forKey:@"EndMonthTime"];
            
            if ([NSJSONSerialization isValidJSONObject:jsonDictionary]){
                NSError *error;
                // 创造一个json从Data, NSJSONWritingPrettyPrinted指定的JSON数据产的空白，使输出更具可读性。
                NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDictionary options:NSJSONWritingPrettyPrinted error:&error];
                NSString *json =[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
                
                //返回页面参数
                responseCallback(json);
            }
        } @catch (NSException *exception) {
            NSLog(@"Native_BasicConfigurationCallback异常情况: %@", exception);
            responseCallback(nil);//返回页面参数
        }
        
    }];
    
    #pragma mark 搜索按钮显示设置
    [bridge registerHandler:@"Native_SearchButtonCallback" handler:^(id data, WVJBResponseCallback responseCallback) {
        NSLog(@"Native_SearchButtonCallback called: %@", data);
        responseCallback(@"Response from testObjcCallback");
        
        WebPushParameterModel *pushParameterModel = [WebPushParameterModel analysisJsonParameter:data];
        if (pushParameterModel == nil) return;
        weakSelf.searchPushParameterModel = pushParameterModel;
        [weakSelf addSearchToNavigationItem];

    }];
    
    #pragma mark 站点按钮显示设置
    [bridge registerHandler:@"Native_StationButtonCallback" handler:^(id data, WVJBResponseCallback responseCallback) {
        NSLog(@"Native_StationButtonCallback called: %@", data);
        responseCallback(@"Response from testObjcCallback");
        //添加站点数据
        [weakSelf setWebTitleHaveStation];
        [weakSelf addStationToNavigationItem];
    }];
    
    #pragma mark 获取选择站点信息
    [bridge registerHandler:@"Native_GetStationInfoCallback" handler:^(id data, WVJBResponseCallback responseCallback) {
        NSLog(@"Native_StationButtonCallback called: %@", data);
        //responseCallback(@"Response from testObjcCallback");
        
        StationInfoEntity *model = [[GetUserStationService sharedService] getSelectStationEntity];
        NSMutableDictionary *jsonDictionary = [NSMutableDictionary dictionary];
        [jsonDictionary setObject:model.stationId forKey:@"StationId"];
        [jsonDictionary setObject:model.stationName forKey:@"StationName"];
        
        if ([NSJSONSerialization isValidJSONObject:jsonDictionary]){
            NSError *error;
            // 创造一个json从Data, NSJSONWritingPrettyPrinted指定的JSON数据产的空白，使输出更具可读性。
            NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDictionary options:NSJSONWritingPrettyPrinted error:&error];
            NSString *json =[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
            
            //返回页面参数
            responseCallback(json);
        }
    }];
    
    #pragma mark 打印页面
    [bridge registerHandler:@"Native_PrintCallback" handler:^(id data, WVJBResponseCallback responseCallback) {
        NSLog(@"Native_PrintCallback called: %@", data);
        //responseCallback(@"Native_PrintCallback from testObjcCallback");
        //添加打印按钮
        [weakSelf addPrintToNavigationItem];
        
    }];
}

#pragma make - Station Notification

-(void)updateStationNotification:(StationInfoEntity*)model
{
    NSMutableDictionary *jsonDictionary = [NSMutableDictionary dictionary];
    [jsonDictionary setObject:model.stationId forKey:@"StationId"];
    [jsonDictionary setObject:model.stationName forKey:@"StationName"];
    
    if ([NSJSONSerialization isValidJSONObject:jsonDictionary]){
        NSError *error;
        // 创造一个json从Data, NSJSONWritingPrettyPrinted指定的JSON数据产的空白，使输出更具可读性。
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDictionary options:NSJSONWritingPrettyPrinted error:&error];
        NSString *json =[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        
        [_bridge callHandler:@"JS_UpdateStationCallback" data:json responseCallback:^(id response) {
            NSLog(@"JS_UpdateStationCallback responded: %@", response);
        }];
    }
}


#pragma mark WKNavigationDelegate

//页面开始加载时调用
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(null_unspecified WKNavigation *)navigation
{
    NSLog(@"didStartProvisionalNavigation");
    //[self.gifLoading setState:CLLoadStateLoading];
}

//当内容开始返回时调用
- (void)webView:(WKWebView *)webView didCommitNavigation:(null_unspecified WKNavigation *)navigation
{
    NSLog(@"didCommitNavigation");
    //[self.gifLoading setState:CLLoadStateFinish];
}

//页面加载完成之后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation
{
    NSLog(@"didFinishNavigation");
    [self.gifLoading setState:CLLoadStateFinish];
}

//页面加载失败时调用
- (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error
{
    NSLog(@"didFailProvisionalNavigation:%@",error);
    [self.gifLoading setState:CLLoadStateFailed];
    self.gifLoading.hidden = NO;
}

//导航错误 404,403,500
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error
{
    NSLog(@"didFailProvisionalNavigation:%@",error);
    [self.gifLoading setState:CLLoadStateFailed];
    self.gifLoading.hidden = NO;
}

#pragma mark BackResultDataDelagate

- (void)backResultDataKey:(id)key dataValue:(id)backValue
{
    //Reload通知页面刷新
    [_bridge callHandler:@"JS_PopBackCallback" data:backValue responseCallback:^(id response) {
        NSLog(@"JS_PopBackCallback responded: %@", response);
    }];
}

#pragma mark UIButtonEvent

- (void)renderButtons:(WKWebView*)webView {
    UIFont* font = [UIFont fontWithName:@"HelveticaNeue" size:12.0];
    
    UIButton *callbackButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [callbackButton setTitle:@"Call handler" forState:UIControlStateNormal];
    [callbackButton addTarget:self action:@selector(callHandler:) forControlEvents:UIControlEventTouchUpInside];
    [self.view insertSubview:callbackButton aboveSubview:webView];
    callbackButton.frame = CGRectMake(10, 400, 100, 35);
    callbackButton.titleLabel.font = font;
    
    UIButton* reloadButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [reloadButton setTitle:@"Reload webview" forState:UIControlStateNormal];
    [reloadButton addTarget:webView action:@selector(reload) forControlEvents:UIControlEventTouchUpInside];
    [self.view insertSubview:reloadButton aboveSubview:webView];
    reloadButton.frame = CGRectMake(110, 400, 100, 35);
    reloadButton.titleLabel.font = font;
}

- (void)callHandler:(id)sender {
    id data = @{ @"greetingFromObjC": @"Hi there, JS!" };
    [_bridge callHandler:@"testJavascriptHandler" data:data responseCallback:^(id response) {
        NSLog(@"testJavascriptHandler responded: %@", response);
    }];
}

- (void)loadExamplePage:(WKWebView*)webView {
    NSString* htmlPath = [[NSBundle mainBundle] pathForResource:@"ExampleApp" ofType:@"html"];
    NSString* appHtml = [NSString stringWithContentsOfFile:htmlPath encoding:NSUTF8StringEncoding error:nil];
    NSURL *baseURL = [NSURL fileURLWithPath:htmlPath];
    [webView loadHTMLString:appHtml baseURL:baseURL];
}

#pragma mark -
#pragma mark IBAction

//搜索按钮跳转
- (void)searchChargeSelector:(id)selector
{
    if(self.searchPushParameterModel)
        [self jumpViewController:self.searchPushParameterModel];
}

//打印网页
- (void)printChargeSelector:(id)selector
{
    [self printWebView:selector];
}

#pragma mark -
#pragma mark 打印文件

/**
 打印文件
 */
- (void)printWebView:(id)sender
{
    //创建打印对象
    UIPrintInteractionController *controller = [UIPrintInteractionController sharedPrintController];
    if(!controller){
        NSLog(@"Couldn't get shared UIPrintInteractionController!");
        [self showErrorHUDText:@"打印失败"];
        return;
    }
    
    // 设置打印机的一些默认信息
    UIPrintInfo *printInfo = [UIPrintInfo printInfo];
    printInfo.outputType = UIPrintInfoOutputGeneral;// 输出类型
    printInfo.jobName = @"XTCloudPrint";// 打印队列名称
    printInfo.duplex = UIPrintInfoDuplexLongEdge;// 是否单双面打印
    controller.printInfo = printInfo;
    
    // 预览设置
    UIPrintPageRenderer *myRenderer = [[UIPrintPageRenderer alloc] init];
    UIViewPrintFormatter *viewFormatter = [self.webView viewPrintFormatter];
    [myRenderer addPrintFormatter:viewFormatter startingAtPageAtIndex:0];
    controller.printPageRenderer = myRenderer;
    
    // 显示页码范围
    controller.showsPageRange = YES;
    
    //打印回执事件
    UIPrintInteractionCompletionHandler completionHandler =
    ^(UIPrintInteractionController *printController, BOOL completed, NSError *error) {
        if(completed){
            [self showSuccessHUDText:@"正在打印"];
            return;
        } else {
            [self showErrorHUDText:@"打印失败"];
            NSLog(@"FAILED! due to error in domain %@ with error code %ld", error.domain, (long)error.code);
        }
    };
    
    // 渲染html
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
        [controller presentFromBarButtonItem:sender animated:YES completionHandler:completionHandler];
    } else {
        [controller presentAnimated:YES completionHandler:completionHandler];
    }
}

@end
